package ms.core.gateway.utils;

import java.util.Date;
import java.util.List;

import ms.core.common.AppException;
import ms.core.common.Page;
import ms.core.common.consts.SysErr;
import ms.core.gateway.bean.SysCorpBean;
import ms.core.gateway.bean.SysLoginBean;
import ms.core.gateway.bean.SysUserBean;
import ms.core.gateway.dao.SysLoginDao;
import ms.core.gateway.response.SysUserVO;
import ms.core.tool.EncryptTool;
import ms.core.tool.IpTableTool;
import ms.core.tool.IpTableTool.IpEntry;
import ms.core.tool.Log4j2Tool;
import ms.core.tool.StrTool;

public class SysLoginUtils {
	private static String confIp = "/config/iptable.dat";

	private SysLoginDao dao;
	public SysLoginUtils() { dao = new SysLoginDao(); }

	private synchronized String getIplocation(String ip) {
		try {
			IpTableTool iptool = IpTableTool.getInstance(confIp);
			IpEntry entry = iptool.queryIp(ip);
			iptool.freeIptable();
			if (entry!=null) return entry.getArea();
		} catch (Exception e) {
			Log4j2Tool.error(SysLoginUtils.class, "纯真IP库初加载失败", e);
		}

		return "未知IP所在地";
	}

	/**
	 * 用户登录
	 * 
	 * @param account
	 * @param password
	 * @param ip 访问者ip
	 * @return 0-帐号不存在或密码错误; 1-成功;
	 */
	public SysUserVO login(String account, String password, String fromIp) {
		SysUserVO usr = SysUserUtils.getUserByAccount(account);

		// 判断用户是否存在
		if (usr==null) throw new AppException(SysErr.USER_USER_NOT_FOUND);

		// 判断密码是否正确
		String pwd = EncryptTool.md5Encode(StrTool.concat(password, usr.getSalt()));
		if (!pwd.equals(usr.getPassword())) throw new AppException(SysErr.USER_LOGIN_ERR);

		// 判断企业是否注销
		if (usr.getCorpState()==SysCorpBean.STATE_DELETE) throw new AppException(SysErr.USER_LOGIN_ERR, "帐号隶属企业已注销,不可登录.");

		// 帐户是否处于未激活或冻结状态
		if (usr.getState()!=SysUserBean.STATE_NORMAL) 
			throw new AppException(SysErr.SYS_ACCESS_FORBID, "帐号状态异常，不可使用.");

		// 更新最后登录时间
		usr.setLoginTime(new Date());
		SysUserUtils.updateLogin(usr.getId(), fromIp, usr.getLoginTime());

		// 写入登录日志
		dao.saveLoginLog(usr.getUid(), usr.getCorpUid(), usr.getAccount(), fromIp, getIplocation(fromIp));
		return usr;
	}
	
	/**
	 * 批量删除日志
	 * 
	 * @param uid
	 * @param ids
	 * @return
	 */
	public int deleteLoginLog(String uid, String ids) {
		List<Long> list = StrTool.splitStringToLongs(ids, ",");
		return dao.deleteLoginLog(uid, list);
	}

	public Page<SysLoginBean> queryLoginLog(String corpId, String uname, int page, int pagesize){
		return dao.queryLogin(corpId, uname, page, pagesize);
	}
}